<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <a-form :form="form">
            <a-form-item style="display:none">
                <a-input v-decorator="['id']"/>
            </a-form-item>
            <a-row>
                <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.name','名称')">
                        <a-input :placeholder="i18n('form.name','名称')" @blur.native="getPinyinByName"
                                 v-decorator="['name', {rules: [{required: true, message: i18n('form.name','名称','input')}]}]"/>
                    </a-form-item>
                </a-col>
                <a-col :span="11">
                    <a-form-item class=" x-a-form-model-error" :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.alias','别名')">
                        <a-input :placeholder="i18n('form.alias','别名')"
                                 v-decorator="['alias', {rules: [
                                     {required: true, message: i18n('form.alias','别名','input')},
                                     {pattern:/^[a-zA-Z][a-zA-Z0-9_-]*$/,message:this.i18n2('form.str','不能以数字开头,不能包含【_-】以外的特殊字符！','input')}
                                     ]}]"/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="24">
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1"
                                 :label="i18n('form.requestAddress','请求地址')">
                        <a-input style="width:60%;" :placeholder="i18n('form.requestAddress','请求地址')"
                                 v-decorator="['url', {rules: [{required: true, message: i18n('form.requestAddress','请求地址','input')}]}]"/>
                        <a-button @click="loadApp" class="biaclick">{{ i18n('form.callRequest', '调用请求') }}</a-button>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.requestMode','请求方式')">
                        <a-select @change="modeSelect" :placeholder="i18n('form.requestMode','请求方式')"
                                  v-decorator="['mode', {initialValue:'RESTFUL',rules: [{required: false, message: i18n('form.requestMode','请求方式','input')}]}]">
                            <a-select-option key="RESTFUL">RESTFUL</a-select-option>
                            <a-select-option key="SOAP">SOAP</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="11">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.requestType','请求类型')">
                        <a-select :placeholder="i18n('form.requestType','请求类型')"
                                  v-decorator="['type', {initialValue:'GET',rules: [{required: true, message: i18n('form.requestType','请求类型','input')}]}]">
                            <a-select-option key="GET">GET</a-select-option>
                            <a-select-option key="POST">POST</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.status','状态')">
                        <a-select :placeholder="i18n('form.status','状态')"
                                  v-decorator="['status', {initialValue:'NO',rules: [{required: false, message:  i18n('form.status','状态','input')}]}]">
                            <a-select-option key="YES">
                                {{ i18n('isStatusMap.enabled', '启用') }}
                            </a-select-option>
                            <a-select-option key="NO">
                                {{ i18n('isStatusMap.disabled', '禁用') }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="11">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.dataType','数据类型')">
                        <a-select @change="itemclick" :placeholder="i18n('form.dataType','数据类型')"
                                  v-decorator="['dataType', {rules: [{required: false, message: i18n('form.dataType','数据类型','input')}]}]">
                            <a-select-option value="application/json">JSON</a-select-option>
                            <a-select-option value="application/x-www-form-urlencoded">
                                {{ i18n('form.pair', '键值对') }}
                            </a-select-option>
                            <a-select-option value="text/xml">XML</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="24">
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1"
                                 :label="i18n('logOrNotMap.logOrNot','是否记录日志')">
                        <a-select v-decorator="['isLog',{initialValue:'NO'}]">
                            <a-select-option value="YES">{{ i18n('logOrNotMap.yes', '是') }}</a-select-option>
                            <a-select-option value="NO">{{ i18n('logOrNotMap.no', '否') }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-tabs v-model="activeKey" class="a-taclick">
                <a-tab-pane :tab="i18n('list.requestConfig','请求头配置')" key="header">
                    <rx-grid ref="header"
                             :showPage="false"
                             :columns="columns"
                             :dataSource="headerFields"
                             style="height: 370px;"
                    >
            <span slot="key" slot-scope="{text,record,index,blur}">
              <a-input v-model="record.key" @blur="onChangeValue(index,'key',text,record,blur)"/>
            </span>
                        <span slot="value" slot-scope="{text,record,index,blur}">
              <a-input v-model="record.value" @blur="onChangeValue(index,'value',text,record,blur)"/>
            </span>
                        <span slot="description" slot-scope="{text,record,index,blur}">
              <a-input v-model="record.description" @blur="onChangeValue(index,'description',text,record,blur)"/>
            </span>
                        <span slot="action" slot-scope="{ text, record }" class="actionIcons">
              <span @click.stop="delRow([record.idx_])">{{ $ti18('rxList.delBtn', '删除') }}</span>
            </span>
                    </rx-grid>
                </a-tab-pane>
                <a-tab-pane :tab="i18n('list.transFerData','传递数据')" key="params" forceRender>
                    <rx-grid ref="params"
                             :showPage="false"
                             :columns="columns"
                             :dataSource="paramsFields"
                             style="height: 370px;"
                    >
            <span slot="key" slot-scope="{text,record,index,blur}">
              <a-input v-model="record.key" @blur="onChangeValue(index,'key',text,record,blur)"/>
            </span>
                        <span slot="value" slot-scope="{text,record,index,blur}">
              <a-input v-model="record.value" @blur="onChangeValue(index,'value',text,record,blur)"/>
            </span>
                        <span slot="description" slot-scope="{text,record,index,blur}">
              <a-input v-model="record.description" @blur="onChangeValue(index,'description',text,record,blur)"/>
            </span>
                        <span slot="action" slot-scope="{ text, record }" class="actionIcons">
              <span @click.stop="delRow([record.idx_])">
                  {{ $ti18('rxList.delBtn', '删除') }}
              </span>
            </span>
                    </rx-grid>
                </a-tab-pane>
                <a-tab-pane v-if="isShow" :tab="i18n('list.requestMsg','请求报文')" key="listHtml" forceRender>
                    <rx-monaco-editor
                        v-model="listHtml"
                        language="json"
                        style="height:300px;"
                    >
                    </rx-monaco-editor>
                </a-tab-pane>
                <a-tab-pane :tab="i18n('list.returnContent','返回内容')" key="responseHtml" forceRender>
                    <a-textarea v-model="responseHtml" :rows="16"/>
                </a-tab-pane>
                <a-tab-pane :tab="i18n('form.responseValid','返回验证')" key="responseValid" forceRender>
                    <rx-monaco-editor
                        ref="responseValid"
                        v-model="responseValid"
                        language="java"
                        style="height:300px;"
                    >
                        <template v-slot:monacoeditor>
                            <a-tooltip style="margin-left: 8px"  placement="rightTop">
                                <template slot="title">
                                    <span>{{i18n("form.responseValidTip","注意：需要return JsonResult对象，result为接口返回内容。例如")
                                    +"：\nimport com.redxun.core.common.entity.JsonResult;\n"
                                    +"return JsonResult.success().setData(result);"}}</span>
                                </template>
                                <a-icon type="question-circle" />
                            </a-tooltip>
                        </template>
                    </rx-monaco-editor>
                </a-tab-pane>
            </a-tabs>
        </a-form>
    </rx-dialog>
</template>
<script>
import SysWebReqDefApi from '@/api/system/core/sysWebReqDef'
import {BaseForm, RxDialog, RxMonacoEditor, RxGrid} from "@lowcode/jpaas-common-lib";

export default {
    name: 'SysWebReqDefEdit',
    mixins: [BaseForm],
    components: {
        RxDialog,
        RxMonacoEditor,
        RxGrid
    },
    data() {
        return {
            activeKey: "header",
            isShow: false,
            responseHtml: "",
            listHtml: "",
            columns: [
                {
                    title: this.i18n('form.key', '键'),
                    dataIndex: 'key',
                    allowCellEdit: true,
                    width: 100,
                    scopedSlots: {customRender: 'key'}
                },
                {
                    title: this.i18n('form.value', '值'),
                    dataIndex: 'value',
                    allowCellEdit: true,
                    width: 100,
                    scopedSlots: {customRender: 'value'}
                },
                {
                    title: this.$comi18('codePreView.explain', '说明'),
                    dataIndex: 'description',
                    allowCellEdit: true,
                    width: 100,
                    scopedSlots: {customRender: 'description'}
                },
                {
                    title: this.$ti18('rxList.action', '操作'),
                    dataIndex: 'action',
                    width: 100,
                    scopedSlots: {customRender: 'action'}
                }
            ],
            headerFields: [{}],
            paramsFields: [{}],
            //返回验证
            responseValid:""
        }
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "sysWebReqDef", key);
        },
        i18n2(name,text,key){
            return this.$ti18(name,text,"formBoEntity",key);
        },
        onload_(values) {
            if (values) {
                if (values.paramsSet) {
                    this.headerFields = JSON.parse(values.paramsSet);
                    this.headerFields.push({});
                }
                if (values.data) {
                    this.paramsFields = JSON.parse(values.data);
                    this.paramsFields.push({});
                }
                if (values.temp) {
                    this.listHtml = values.temp;
                }
                if (values.responseValid) {
                    this.responseValid = values.responseValid;
                }
                this.initMode(values.mode, values.dataType);
            }
        },
        get(id) {
            return SysWebReqDefApi.get(id);
        },
        save(values) {
            var d1 = this.$refs["header"];//请求头设置
            var d2 = this.$refs["params"];//传递数据
            var header = JSON.stringify(this.parseGridData(d1.getData()));
            var body = JSON.stringify(this.parseGridData(d2.getData()));
            values.paramsSet = header;
            values.data = body;
            values.temp = this.listHtml;
            values.appId = this.$parent.curApp.appId;
            values.responseValid = this.responseValid;
            return SysWebReqDefApi.save(values);
        },
        delRow(idx_) {
            var grid = this.$refs[this.activeKey];
            if (grid.getData().length <= 1) {
                this.$message.error(this.i18n('form.deletion', '不允许删除最后一位参数!'));
                return;
            }
            grid.removeRows(idx_);
        },
        getPinyinByName() {
            let name = this.form.getFieldsValue().name
            if (!name) {
                return;
            }
            if (this.form && this.form.getFieldsValue().alias) {
                return;
            }
            this.getPinyin(name).then(res => {
                //去除不可见的特殊符号
                if (res) {
                    res = res.replace(/\u200B/g, '');
                }
                this.form.setFieldsValue({alias: res})
            })
        },
        parseGridData(data) {
            var ary = [];
            var idx = 0;
            for (var i = 0; i < data.length; i++) {
                var obj = {};
                obj.key = data[i].key;
                obj.value = data[i].value;
                obj.description = data[i].description;
                if (this.isEmpty(obj.key)) continue;
                ary[idx++] = obj;
            }
            return ary;
        },
        isEmpty(str) {
            if (!str || str == "") {
                return true;
            }
            return false;
        },
        onChangeValue(index, dataIndex, text, record, blur) {
            blur(index, dataIndex, record[dataIndex], record);
            var grid = this.$refs[this.activeKey];

            if (record.key == "" && record.value == "") {
                if (grid.getData().length > 1) {
                    grid.removeRows([record.idx_]);
                }
            }
            if (grid.getData().length <= index + 1 && text) {
                grid.addRow({});
            }
        },
        initMode(value, val) {
            if (value == "RESTFUL") {
                if (val == "application/json") {
                    this.isShow = true;
                } else {
                    this.isShow = false;
                }
            }
            if (value == "SOAP") {
                this.isShow = true;
            }
        },
        modeSelect(value) {
            var val = this.form.getFieldValue("dataType");
            this.initMode(value, val);
        },
        itemclick(value) {
            var grid = this.$refs['header'];
            var val = this.form.getFieldValue("mode");
            var dataType = this.form.getFieldValue("dataType");
            this.initMode(val, value);
            var row = grid.findRows(function (row) {
                if (row.key == "Content-Type") return true;
            })[0];
            if (!row) {
                grid.addRow({key: "Content-Type", value: value + ";charset=UTF-8", description: ""});
            } else {
                if (value != dataType) {
                    grid.updateRow(row, {value: value + ";charset=UTF-8"});
                }
            }
        },
        loadApp() {
            //请求方式
            var mode = this.form.getFieldValue("mode");
            //请求类型
            var type = this.form.getFieldValue("type");
            //请求地址
            var url = this.form.getFieldValue("url");
            var d1 = this.$refs["header"];//请求头设置
            var d2 = this.$refs["params"];//传递数据
            if (!url) {
                this.$message.error(this.i18n('form.requestAddressIsEmpty', '请求地址为空!'));
                return;
            }
            SysWebReqDefApi.execute({
                mode: mode, url: url, type: type,
                header: JSON.stringify(this.parseGridData(d1.getData())),
                body: JSON.stringify(this.parseGridData(d2.getData())),
                temp: this.listHtml,
                responseValid:this.responseValid
            }).then(res => {
                if (res.success) {
                    this.responseHtml = res.data;
                    this.activeKey = "responseHtml";
                }
            })
        }
    }
}
</script>
<style scoped>
.a-taclick {
    width: calc(100% - 30px);
    margin: auto;
}

.biaclick {
    margin-left: 15px;
}
</style>
